import { archService } from "@/mdesign-lib/mdesign-app.umd.js";
import { Action, ActionKey } from "@/mdesign-lib/mdesign-app.umd.js";
import { localFile } from "@/mdesign-lib/mdesign-app.umd.js";
import { loading } from "@/mdesign-lib/mdesign-app.umd.js";
import { DiagramTableEditor } from "@/mdesign-lib/mdesign-app.umd.js";
import { writeFile } from "fs/promises";

export class TableExportJsonAction extends Action {
  keyName = "tableExportJson" as ActionKey;
  desc = "导出Excel";

  async onTableToolbarClick(tableEditor: DiagramTableEditor) {
    const res = await localFile.chooseSaveFilePath({
      title: "选择保存的位置",
      filters: [
        {
          name: "Json Files",
          extensions: ["json"]
        }
      ],
      defaultPath: tableEditor.tab.diagramName
    });
    const filePath = res.filePath;
    if (res.canceled || !filePath) return;
    loading.popup("正在导出...");

    archService
      .getScenarioJsonData(tableEditor.projectId, tableEditor.modelId)
      .then(async data => {
        const jsonStr = JSON.stringify(data);
        await writeFile(filePath, jsonStr);
        app.$notify({
          type: "success",
          title: "成功",
          message: "导出成功"
        });
      })
      .finally(() => {
        loading.close();
      });
  }
}
